package global

import (
	"errors"
	"github.com/go-resty/resty/v2"
	"net/http"
)

type RestData[T interface{}] struct {
	Status int    `json:"status"`
	Text   string `json:"text"`
	Result T      `json:"result"`
}

func UrlRequest[T interface{}](url, method string, query map[string]string, body any, dataOut *RestData[T]) error {
	return HttpRequest[RestData[T]](url, method, query, body, dataOut)
}

func HttpRequest[T interface{}](url, method string, query map[string]string, body any, dataOut *T) error {
	req := resty.New().R().ForceContentType("application/json")
	if dataOut != nil {
		req.SetResult(dataOut)
	}
	if len(query) > 0 {
		req.SetQueryParams(query)
	}
	req.SetBody(body)
	var err error
	switch method {
	case http.MethodGet:
		_, err = req.Get(url)
	case http.MethodPost:
		_, err = req.Post(url)
	case http.MethodPut:
		_, err = req.Put(url)
	case http.MethodDelete:
		_, err = req.Delete(url)
	case http.MethodOptions:
		_, err = req.Options(url)
	default:
		return errors.New("not support")
	}
	return err
}
